<!doctype html>
<html>
<title>贪吃蛇小游戏</title>
<body background="__BG_IMG__" style="width: 100%;height: 100%;background-size: 100%">
<div style="position: absolute;left: 50%;top: 50%;transform: translate(-50%,-50%)">
    <canvas id="can" width="400" height="400" style="background:pink;border-radius: 10px"></canvas>
</div>
<div style="position: absolute;left: 50%;top: 50%;transform: translate(-50%,-50%)" id="start">
    <input style="height: 30px" class="a-upload" type="submit" value="开始游戏" onclick="start()">
</div>
<script>
    //sn//dz身体矩形块坐标//fx//ctx画布
    var sn=[42,41],dz=43,fx=1,n,ctx=document.getElementById("can").getContext("2d");
    function draw(t,c){
        //生成食物
        ctx.fillStyle=c;
        ctx.fillRect(t%20*20+1,~~(t/20)*20+1,18,18);
    }
    //操控贪吃蛇
    document.onkeydown=function(e){
        fx=sn[1]-sn[0]==(n=[-1,-20,1,20][(e||event).keyCode-37]||fx)?fx:n
    };
    function start(){
        //隐藏开始游戏按钮
        document.getElementById("start").style.display="none";
        //
        sn.unshift(n=sn[0]+fx);
        if(sn.indexOf(n,1)>0 || n<0 || n>399 || fx==1&&n%20==0 || fx==-1 && n%20==19) {
            //判断是否结束游戏
            alert("GAME OVER");location.href="";
        }
        draw(n,"Lime");
        if(n==dz){
            //已成功吃到食物
            while(sn.indexOf(dz=~~(Math.random()*400))>=0);
            draw(dz,"Yellow");
        }else
            draw(sn.pop(),"pink");
        setTimeout(arguments.callee,200);
    }
</script>
<style>
    .a-upload {
        padding: 4px 10px;
        height: 20px;
        line-height: 20px;
        position: relative;
        cursor: pointer;
        color: #888;
        background: #fafafa;
        border: 1px solid #ddd;
        border-radius: 4px;
        overflow: hidden;
        display: inline-block;
        *display: inline;
        *zoom: 1
    }
    .a-upload  input {
        position: absolute;
        font-size: 100px;
        text-align: center;
        right: 0;
        top: 0;
        opacity: 0;
        filter: alpha(opacity=0);
        cursor: pointer
    }
    .a-upload:hover {
        color: #444;
        background: #eee;
        border-color: #ccc;
        text-decoration: none
    }
</style>
</body>
</html>